<template>
  <n-grid :cols="24">
    <n-grid-item span="24">
      <detail-page-header title="快速修改SKU"> </detail-page-header>
      <div class="mt-[16px]"></div>
      <n-grid-item span="24">
        <n-data-table
          :bordered="false"
          :columns="columns"
          :style="{ height: `66vh` }"
          :loading="tableLoading"
          :data="variantsList"
        />
      </n-grid-item>
    </n-grid-item>
  </n-grid>
</template>
<script setup lang="ts">
import { ref, onMounted, h } from "vue";
import { cloneDeep, get, isEmpty } from "lodash-es";
import { NButton, NDropdown, NIcon, NInput, NInputNumber, NSwitch } from "naive-ui";
import { CreateOutline, InformationCircleOutline } from "@vicons/ionicons5";
import {
  getVariantsByProductId,
  updateVariantById,
} from "@/api/product/product.api";
import { getAllAttributes } from "@/api/product/productAttribute.api";
import { IProductVariantsProps } from "./props";

const props = defineProps<IProductVariantsProps>();

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    fixed: "left",
    width: "5%",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "SKU名称",
    key: "name",
    width: "10%",
  },
  {
    title: "SKU编码",
    key: "sku",
    width: "15%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInput, {
          size: "small",
          value: row.sku,
          onUpdateValue(v) {
            row.sku = v;
          },
        });
      } else {
        return h("span", get(row, "sku"));
      }
    },
  },
  {
    title: "建议零售价",
    key: "soldPrice",
    width: "10%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInputNumber, {
          size: "small",
          value: row.soldPrice,
          onUpdateValue(v) {
            row.soldPrice = v;
          },
        });
      } else {
        return h("span", get(row, "soldPrice"));
      }
    },
  },
  {
    title: "促销价",
    key: "promotionPrice",
    width: "10%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInputNumber, {
          size: "small",
          value: row.promotionPrice,
          onUpdateValue(v) {
            row.promotionPrice = v;
          },
        });
      } else {
        return h("span", get(row, "promotionPrice"));
      }
    },
  },
  {
    title: "建议回收价",
    key: "recTradeinPrice",
    width: "10%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInputNumber, {
          size: "small",
          value: row.recTradeinPrice,
          onUpdateValue(v) {
            row.recTradeinPrice = v;
          },
        });
      } else {
        return h("span", get(row, "recTradeinPrice"));
      }
    },
  },
  {
    title: "最低回收价",
    key: "minTradeinPrice",
    width: "10%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInputNumber, {
          size: "small",
          value: row.minTradeinPrice,
          onUpdateValue(v) {
            row.minTradeinPrice = v;
          },
        });
      } else {
        return h("span", get(row, "minTradeinPrice"));
      }
    },
  },
  {
    title: "状态",
    key: "status",
    width: "5%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      return h(NSwitch, {
        size: "small",
        checkedValue: "1",
        uncheckedValue: "2",
        disabled: !isEdit,
        value: row.status,
        onUpdateValue(v) {
          row.status = v;
        },
      });
    },
  },
  {
    title: "重量",
    key: "weight",
    width: "8%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (isEdit) {
        return h(NInputNumber, {
          size: "small",
          value: row.weight,
          onUpdateValue(v) {
            row.weight = v;
          },
        });
      } else {
        return h("span", get(row, "weight"));
      }
    },
  },
  {
    title: "操作",
    key: "action",
    width: "5%",
    render: (row: any) => {
      const isEdit = get(row, "isEdit");
      if (!isEdit) {
        return h(
          NButton,
          {
            size: "small",
            strong: true,
            secondary: true,
            onClick: () => handleEditVariant(row),
          },
          {
            icon: () =>
              h(NIcon, {
                component: CreateOutline,
              }),
          }
        );
      } else {
        return h(
          NDropdown,
          {
            options: [
              {
                label: "保存",
                key: "confirm",
              },
              {
                label: "取消",
                key: "cancel",
              },
            ],
            trigger: "hover",
            onSelect: (key) => handleDropdownSelect(key, row),
          },
          () =>
            h(
              NButton,
              {
                size: "small",
                type: "success",
                strong: true,
                secondary: true,
              },
              {
                icon: () =>
                  h(NIcon, {
                    component: InformationCircleOutline,
                  }),
              }
            )
        );
      }
    },
  },
];

const tableLoading = ref<boolean>(false);
const attributes = ref<any[]>([]);
const variantsList = ref<any[]>([]);

const editingVariant = ref<any>({});

const handleGetVariants = async () => {
  tableLoading.value = true;
  try {
    const result = await getVariantsByProductId(props.prodcutId);
    variantsList.value = get(result, "result") || [];
  } finally {
    tableLoading.value = false;
  }
};

const handleGetAllAttributes = async () => {
  const res = await getAllAttributes();
  const _attributes = get(res, "result") || [];
  attributes.value = _attributes.map((item: any) => {
    return {
      ...item,
      isEdit: false,
    };
  });
};

const resetEditingVariant = () => {
  if (!isEmpty(editingVariant.value)) {
    let selectedVariant = variantsList.value.find(
      (item) => item.id === editingVariant.value.id
    );

    if (selectedVariant) {
      selectedVariant.sku = editingVariant.value.sku;
      selectedVariant.soldPrice = editingVariant.value.soldPrice;
      selectedVariant.promotionPrice = editingVariant.value.promotionPrice;
      selectedVariant.recTradeinPrice = editingVariant.value.recTradeinPrice;
      selectedVariant.minTradeinPrice = editingVariant.value.minTradeinPrice;
      selectedVariant.status = editingVariant.value.status;
      selectedVariant.weight = editingVariant.value.weight;
      selectedVariant.isEdit = false;
    }
  }
};

const handleEditVariant = (payload: any) => {
  resetEditingVariant();
  payload.isEdit = true;
  editingVariant.value = cloneDeep(payload);
};

const handleUpdateVariant = async (payload: any) => {
  const params = {
    id: payload.id,
    sku: payload.sku,
    soldPrice: payload.soldPrice,
    promotionPrice: payload.promotionPrice,
    recTradeinPrice: payload.recTradeinPrice,
    minTradeinPrice: payload.minTradeinPrice,
    weight: payload.weight,
    status: payload.status,
  };

  const result = await updateVariantById(params);
  payload.isEdit = false;
  console.log(result);
};

const handleCancelUpdate = (payload: any) => {
  resetEditingVariant();
  payload.isEdit = false;
};

const handleDropdownSelect = (key: string, payload: any) => {
  // 取消或者保存
  if (key === "confirm") {
    handleUpdateVariant(payload);
  } else {
    handleCancelUpdate(payload);
  }
};

onMounted(() => {
  handleGetVariants();
  handleGetAllAttributes();
});
</script>
